﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acme.Sakila.TestSite.Objects;
using Acme.Sakila.EFDAL;
using Acme.Sakila.EFDAL.Entity;

namespace Acme.Sakila.TestSite
{
	public partial class FilmItem : BasePersistablePage
	{
		#region Page Events

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			cmdSave.Click += new EventHandler(SaveData);
			cmdCancel.Click += new EventHandler(cmdCancel_Click);
		}

		#endregion

		#region Methods

		protected override nHydrate.EFCore.DataAccess.NHEntityObject CreateObject(SakilaEntities context)
		{
			var newItem = new Acme.Sakila.EFDAL.Entity.film();
			context.AddItem(newItem);
			return newItem;
		}

		protected override void SetupBindings(SakilaEntities context)
		{
			var filmId = this.Request["id"].ToInt32();
			var theFilm = context.film.FirstOrDefault(x => x.film_id == filmId);
			if (theFilm == null)
				theFilm = CreateObject(context) as Acme.Sakila.EFDAL.Entity.film;

			Mapper.InitializeList(cboLanguage, context.language.ToList(), Acme.Sakila.EFDAL.Entity.language.FieldNameConstants.name, Acme.Sakila.EFDAL.Entity.language.FieldNameConstants.language_id);

			Mapper.Map(lblFilmId, theFilm, Acme.Sakila.EFDAL.Entity.film.FieldNameConstants.film_id);
			Mapper.Map(txtTitle, theFilm, Acme.Sakila.EFDAL.Entity.film.FieldNameConstants.title, lblTitle);
			Mapper.Map(txtDescription, theFilm, Acme.Sakila.EFDAL.Entity.film.FieldNameConstants.description, lblDescription);
			Mapper.Map(txtReleaseYear, theFilm, Acme.Sakila.EFDAL.Entity.film.FieldNameConstants.release_year, lblReleaseYear);
			Mapper.Map(cboLanguage, theFilm, Acme.Sakila.EFDAL.Entity.film.FieldNameConstants.language_id, lblLanguage);

			//Calculate the take for this film
			decimal total = 0;
			if (filmId != null)
				total = context.payment.Where(x => x.rental.inventory.film.film_id == filmId).Sum(x => x.amount);
			lblTotal.Text = total.ToString("$###,###,##0.00");

			linkActors.NavigateUrl = "/ActorList.aspx?filmid=" + filmId;

		}

		#endregion

		#region Event Handlers

		private void cmdCancel_Click(object sender, EventArgs e)
		{
			this.Response.Redirect(SessionHelper.LastFilmListSearch);
		}

		protected override void OnDataSavedSucess(EventArgs e)
		{
			base.OnDataSavedSucess(e);
			this.Response.Redirect(SessionHelper.LastFilmListSearch);
		}

		#endregion

	}
}